package org.linlinjava.litemall.wx.web;

import com.sun.corba.se.spi.presentation.rmi.IDLNameTranslator;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrderInvoice;
import org.linlinjava.litemall.db.service.LitemallOrderInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@RestController
@RequestMapping("/wx/orderInvoice")
public class WxOrderInvoiceController {
    private final Log log= LogFactory.getLog(WxOrderInvoiceController.class);
    /**
     * 订单中的发票信息和这个相同..05.10独立出来 但验证复制一份在 wx/order/parseOrder
     */
    @Autowired
    private LitemallOrderInvoiceService orderInvoiceService;

    /**
     * 票据信息 invoiceType  的 1个人 2公司 3增值
     */
    private static final String  INVOICE_NO1 = String.valueOf(1);
    private static final String  INVOICE_NO2 =String.valueOf(2);
    private static final String  INVOICE_NO3 = String.valueOf(3);
    //个人拥有最多票据信息 条数 (个人+ 公司 + 增值税票)  测试时候可以改为 100
    private static final Integer PersonalInvoiceMax = 10;


    /**
     * (删除)增加票据信息  不能  超过10个  下边的接口可以完全实现..但是前端要求再提供一个接口..保存  普通发票>个人 信息
     */

    /**
     * 4增加票据信息   票据信息保存   不能  超过10个
     * @param orderInvoice
     * @param request
     * @return
     */
    @PostMapping("/add")
    public  Object addOrderInvoice(@RequestBody LitemallOrderInvoice orderInvoice, HttpServletRequest request){
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        if (user == null) {
            return ResponseUtil.unlogin(); }
        Integer userId = Integer.parseInt(user.getUserid());
        System.out.println("orderInvoice>>>>>>" + orderInvoice);
        //根据发票类型  决定  1普:个人:抬头  2普:公司:抬头/税号  3 增值:全部
        String invoiceType = orderInvoice.getInvoiceType();
        System.out.println("invoiceType>>>>>>" + invoiceType);
        String invoiceTitle = orderInvoice.getInvoiceTitle();
        String invoiceNo = orderInvoice.getInvoiceNo();
        String invoiceAddress = orderInvoice.getInvoiceAddress();
        String invoicePhone = orderInvoice.getInvoicePhone();
        String invoiceBank = orderInvoice.getInvoiceBank();
        String invoiceAccount = orderInvoice.getInvoiceAccount();

        //如果 是Type1普通发票/个人   {"invoiceTitle":"个人名称可以不写","invoiceType":"1"}
        if(StringUtils.isEmpty(invoiceType) ||  !INVOICE_NO1.equals(invoiceType)
                && !INVOICE_NO2.equals(invoiceType) &&  !INVOICE_NO3.equals(invoiceType)
        ){ return ResponseUtil.fail(402,"请确认票据类别");}
        if( INVOICE_NO1.equals(invoiceType)){
            //普通票个人..不能有其他信息进来
            System.out.println("普通发票>>>>>>个人>>>>>" + invoiceType);
            if(StringUtils.isNotEmpty(invoiceNo) || StringUtils.isNotEmpty(invoiceAddress) || StringUtils.isNotEmpty(invoicePhone)
                    ||  StringUtils.isNotEmpty(invoiceBank) ||  StringUtils.isNotEmpty(invoiceAccount)  ){
                throw new  RuntimeException("个人发票不能携带出名称外其他信息");
            }
            invoiceType = INVOICE_NO1;
            //如果 票据抬头不为空..则不能超过20位
            if(StringUtils.isNotEmpty(invoiceTitle)){
                if(invoiceTitle.length() >20){
                    throw new  RuntimeException("不能超过20位");
                }
            }
        }
        //Type2普通发票/公司:::   {"invoiceTitle":"的","invoiceNo":"123123","invoiceType":"2"}
        if( INVOICE_NO2.equals(invoiceType)){
            System.out.println("普通发票>>>>>>公司>>>>>" + invoiceType);
            if(StringUtils.isEmpty(invoiceTitle)){
                return ResponseUtil.fail(402,  "公司名称不能为空");
            }
            if(StringUtils.isEmpty(invoiceNo)){
                return ResponseUtil.fail(402, "税号不能为空");
            }
            boolean invoiceNoLegal = invoiceNo.length() != 15 && invoiceNo.length() != 18 && invoiceNo.length() != 20;
            if(invoiceNoLegal){
                return ResponseUtil.fail(402, "请确认发票税号位数:15(旧),18(新)或20(特殊)");
            }
            if( StringUtils.isNotEmpty(invoiceAddress) || StringUtils.isNotEmpty(invoicePhone)
                    ||  StringUtils.isNotEmpty(invoiceBank) ||  StringUtils.isNotEmpty(invoiceAccount)  ){
                return ResponseUtil.fail(402, "公司票据信息除了名称/税号,不能携带其他信息");
            }
        }
        //Typ3增值税专用发票  全部数据
        if(INVOICE_NO3.equals(invoiceType)){
           System.out.println("增值税发票>>>>>>>>>>>" + invoiceType);
           if(StringUtils.isEmpty(invoiceTitle)){return ResponseUtil.fail(402,  "发票抬头:个人/公司名称"); }
           //税号一般分为 15. 18(最常见) 20 位(增值见)..&&只要有一个条件不一样就是不满足
           if(StringUtils.isEmpty(invoiceNo)){
               return ResponseUtil.fail(402, "发票税号不能为空");
           }
            boolean invoiceNoLegal = invoiceNo.length() != 15 && invoiceNo.length() != 18 && invoiceNo.length() != 20;
            if(invoiceNoLegal){
                return ResponseUtil.fail(402, "请确认发票税号位数:15(旧),18(新)或20(特殊)");
            }
           //发票地址,个人/公司地址,XX省XX市XX县/区
           if(StringUtils.isEmpty(invoiceAddress) || invoiceAddress.length() < 10 ){
               return ResponseUtil.fail(402, "请确认个人/公司地址,不少于10个字");
           }
           if (!RegexUtil.isMobileExact(invoicePhone)) { return ResponseUtil.fail(402, "手机号格式不正确"); }

           //开户行:中国XX银行股份有限公司XX支行
           if(StringUtils.isEmpty(invoiceBank) || invoiceBank.length() <= 6 ){
               return ResponseUtil.fail(402, "开户行:中国XX银行股份有限公司XX支行"); }

           //银行账户长度::银行卡规范个人银行卡长度范围13-19位，企业对公账号银行卡范围，前不久看到的长度范围最少8位，最多28位

           if(StringUtils.isEmpty(invoiceAccount) || invoiceAccount.length() <= 8 ){
               return ResponseUtil.fail(402, "银行账户长度不得少于8位"); }
       }

        //根据 用户ID  查找票据信息
        String orderSN = "";
        Integer defaultInvoiceInt = null;
        String  invoiceTypeFind  = "";
        List<LitemallOrderInvoice> orderInvoiceList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,invoiceTypeFind);
        int size =orderInvoiceList.size();
        //★★★★★★★★★★★★★注意测试时候先可以注册100个发票 实际不得超过10个
        if (size >= PersonalInvoiceMax){return ResponseUtil.fail(402,"票据信息保存超过10个");}
        else {
            if (size <= 0) {
                //如果没有票据 信息.设置默认
                orderInvoice.setDefaultInvoice(1);
            }else {
            orderInvoice.setDefaultInvoice(0);}
            orderInvoice.setUserId(userId);
            orderInvoice.setInvoiceTitle(invoiceTitle);
            orderInvoice.setInvoiceNo(invoiceNo);
            orderInvoice.setInvoiceAddress(invoiceAddress);
            orderInvoice.setInvoicePhone(invoicePhone);
            orderInvoice.setInvoiceBank(invoiceBank);
            orderInvoice.setInvoiceAccount(invoiceAccount);
            orderInvoice.setInvoiceType(invoiceType);
            orderInvoice.setAddTime(LocalDateTime.now());
            orderInvoiceService.addOrderInvoice(orderInvoice);
        }
        return ResponseUtil.ok();
    }

    /**
     *1 显示本人所有的  票据信息
     * @param request
     * @return
     */
    @GetMapping("/allInvoiceInfo")
    public  Object allInvoice( HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        Integer userId = Integer.parseInt(user.getUserid());
        String orderSN = "";
        Integer defaultInvoiceInt = null;
        String  invoiceType = "";
        List<LitemallOrderInvoice>     invoiceList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,invoiceType);
        //个人票据信息
//       List<LitemallOrderInvoice>      personalList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,INVOICE_NO1);
//        List<LitemallOrderInvoice>      companyList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,INVOICE_NO2);
//        List<LitemallOrderInvoice>      specialList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,INVOICE_NO3);

        Map<String,Object> data = new HashMap<>(3);
        //personal
        data.put("total",invoiceList.size());
        data.put("list",invoiceList);
        return ResponseUtil.ok(data);
    }

    /**
     * 2设置默认的  票据信息   把原来票据信息都变为0
     * @param invoiceId
     * @return
     */
    @GetMapping("/default/{invoiceId}")
    public  Object defaultInvoice(@PathVariable("invoiceId") Integer invoiceId,HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        Integer userId = Integer.parseInt(user.getUserid());

        String orderSN = "";
        Integer defaultInvoiceInt = 1;
        String  invoiceType = "";
        List<LitemallOrderInvoice> orderInvoiceList = orderInvoiceService.findOrderInvoiceList(userId, orderSN,defaultInvoiceInt,invoiceType );
      Integer size=   orderInvoiceList.size();
        log.info("size>>>" + size);
       //如果有默认..把原来默认改为 0
        if(  orderInvoiceList.size() > 0 ){
            log.info("原来默认票据信息删除.重新设置");
            LitemallOrderInvoice litemallOrderInvoice = orderInvoiceList.get(0);
            //把原来票据信息都变为0  默认为1
            litemallOrderInvoice.setDefaultInvoice(0);
            orderInvoiceService.updateOrderInvoice(litemallOrderInvoice);
        }
        log.info("设置默认票据信息");
        LitemallOrderInvoice byPrimaryKey = orderInvoiceService.findByPrimaryKey(invoiceId);
        byPrimaryKey.setDefaultInvoice(1);
        orderInvoiceService.updateOrderInvoice(byPrimaryKey);
        return ResponseUtil.ok();
    }

    /**
     * 3删除 票据信息
     * @param invoiceId   订单票据ID
     * @return
     */
    @DeleteMapping("/delInvoice/{invoiceId}")
    public  Object delInvoice(@PathVariable("invoiceId") Integer invoiceId,HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        orderInvoiceService.delOrderInvoice(invoiceId);
        return ResponseUtil.ok();
    }

    /**
     * 5更改票据信息
     * @param orderInvoice 订单票据信息
     * @return
     */
    @PutMapping("/updateInvoice")
    public  Object updateInvoice(@RequestBody LitemallOrderInvoice orderInvoice,HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        orderInvoiceService.updateOrderInvoice(orderInvoice);
        return ResponseUtil.ok();
    }



}
